
// 将秒数转为字符串
function timeToString(secs) {

    let hours = Math.floor(secs / 3600);
    let minutes = Math.floor((secs % 3600) / 60);
    let secondsLeft = Math.floor(secs) % 60;

    // 补零操作
    hours = hours < 10 ? '0' + hours : hours;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    secondsLeft = secondsLeft < 10 ? '0' + secondsLeft : secondsLeft;

    return `${hours}:${minutes}:${secondsLeft}`;
}

var db
function database() {
    if(db === undefined || db === null) {
        initDatabase()
    }

    return db
}

// 初始化本地数据库
function initDatabase(){
    db = LocalStorage.openDatabaseSync("BNSPlayer", "1.0", "BNSPlayer's user profile", 1000000)
    try {
        db.transaction(function (tx) {
            tx.executeSql("CREATE TABLE IF NOT EXISTS keyValues (key TEXT PRIMARY KEY NOT NULL, value TEXT)")
            tx.executeSql("CREATE TABLE IF NOT EXISTS playHistory (filename TEXT PRIMARY KEY NOT NULL, timepoint REAL, writeTime INTEGER)")
        })
    } catch (err) {
        console.log("Error creating table in database: " + err)
    };

    console.log("LocalStorage path: ", LocalStorage.path);
}

function value(key) {

    var ret = ""

    try{

        database().transaction(function (tx) {
            var res = tx.executeSql("SELECT value FROM keyValues WHERE key=?", [key])
            if(res.rows.length > 0) {
                ret = res.rows.item(0).value
            }
        })
    } catch (err) {
        console.log("Error searching in database: " + err)
    };

    return ret
}

function setValue(key, value) {
    try{
        database().transaction(function (tx) {
            tx.executeSql("INSERT INTO keyValues (key, value) VALUES (?, ?) \
                ON CONFLICT(key) DO UPDATE SET value=excluded.value", [key, value])
        })
    } catch (err) {
        console.log("Error inserting in database: " + err)
    };
}

function playHistory(file) {

    var ret = 0

    try{
        database().transaction(function (tx) {
            var res = tx.executeSql("SELECT timepoint FROM playHistory WHERE filename = ?", [file])
            if(res.rows.length >= 1) {
                ret = Number(res.rows.item(0).timepoint)
            }
        })
    } catch (err) {
        console.log("Error searching in database: " + err)
    };

    return ret
}

function setPlayHistory(file, timepoint) {
    try{
        database().transaction(function (tx) {

            var now = Date.now()
            tx.executeSql("INSERT INTO playHistory (filename, timepoint, writeTime) VALUES (?, ?, ?) \
                                ON CONFLICT(filename) DO UPDATE SET timepoint=excluded.timepoint, writeTime=excluded.writeTime;",
                                [file, timepoint.toString(), now.toString()])
        })
    } catch (err) {
        console.log("Error inserting in database: " + err)
    };
}

// 将URL转为本地地址
function urlToLocalFile(url) {
    var s = url.toString().substring(7);
    return s.substring(Qt.platform.os == "windows" ? 1 : 0);
}

// 从URL获取文件的名字
function baseNameFromURL(url) {
    var filename = urlToLocalFile(url)
    var lastSlashIndex = filename.lastIndexOf('/')
    return filename.substring(lastSlashIndex + 1)
}

// 从URL获取文件所在目录
function dirFromURL(url) {
    var filename = urlToLocalFile(url)
    var lastSlashIndex = filename.lastIndexOf('/')
    return filename.substring(0, lastSlashIndex)
}

function localPathToURL(localPath) {
    return new URL((Qt.platform.os == "windows" ? "file:///" : "file://")  + localPath)
}
